 <template>
  <div>

    <div class="news-main">

      <top-bar @updateNewsByType='getNewsByType'>
      </top-bar>

      <div>

        <el-table :data="articleData"
                  style="width: 100%"
                  :show-header="false"
                  v-if="showAllNews"
                  :key="Math.random()">

          <el-table-column :key="Math.random()">

            <template slot-scope="scope">
              <el-row>
                <el-col :span="20">
                  <div class="news-content">{{scope.row.newsContent}}</div>
                </el-col>
              </el-row>
              <el-row :id="scope.row.idNews">
                <el-col :span="10"
                        :offset="6">
                  <div class="文本">
                    {{scope.row.newsComments}}评论
                    {{scope.row.newsStars}}收藏
                    · {{scope.row.newsUpdatetime}}

                    <template v-if="scope.row.stared">
                      <el-button icon="el-icon-star-on"
                                 type="success"
                                 :disabled="MyidUser == 0"
                                 round
                                 class="str-btn"
                                 @click="deleteNewsStar(scope.row,false,scope.$index)"></el-button>
                    </template>
                    <template v-else>
                      <el-button icon="el-icon-star-off"
                                 type="primary"
                                 round
                                 class="str-btn"
                                 :disabled="MyidUser == 0"
                                 @click="addNewsStar(scope.row,false,scope.$index)"></el-button>
                    </template>

                  </div>
                </el-col>
                <el-col :span="4"
                        class="详情">
                  <el-button type="text"
                             @click.stop="showDetail(scope.row, scope.$index)"
                             class="show-detail-btn">查看详情</el-button>
                </el-col>

              </el-row>
            </template>
          </el-table-column>
        </el-table>

        <el-table :data="NewsDetail"
                  style="width: 100%"
                  :show-header="false"
                  v-if="showDetailNews"
                  :key="Math.random()">

          <el-table-column :key="Math.random()">

            <template slot-scope="scope">
              <el-row>

                <el-col :span="20">
                  <el-button type='primary'
                             class="refresh-btn"
                             @click="Refresh"
                             round>返回</el-button>

                  <div class="news-content">{{scope.row.newsContent}}</div>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="10"
                        :offset="6">
                  <div class="文本">
                    {{scope.row.newsComments}} 评论
                    {{scope.row.newsStars}} 收藏
                    · {{scope.row.newsUpdatetime}}

                    <template v-if="scope.row.stared">
                      <el-button icon="el-icon-star-on"
                                 type="success"
                                 :disabled="MyidUser == 0"
                                 round
                                 class="str-btn"
                                 @click="deleteNewsStar(scope.row,true,scope.$index)"></el-button>
                    </template>
                    <template v-else>
                      <el-button icon="el-icon-star-off"
                                 type="primary"
                                 round
                                 class="str-btn"
                                 :disabled="MyidUser == 0"
                                 @click="addNewsStar(scope.row,true,scope.$index)"></el-button>
                    </template>

                  </div>
                </el-col>

              </el-row>
            </template>
          </el-table-column>

        </el-table>

        <div class="foot-page"
             v-if="!showDetailNews">
          <el-button type="primary"
                     @click="previousPage"> 上一页</el-button>
          第{{currentPage}}页, 共{{allPages}}页
          <el-button type="primary"
                     @click="nextPage"> 下一页</el-button>

        </div>

        <el-form v-if="showDetailNews">
          <el-form-item labelPosition="top"
                        class="comment-input">
            <el-input type="textarea"
                      :rows="2"
                      :placeholder="commentPlaceHolder"
                      v-model="commentContent"
                      :disabled="MyidUser == 0">
            </el-input>
          </el-form-item>
          <el-form-item class="input-btn">
            <el-button type="primary"
                       :disabled="MyidUser == 0"
                       @click="onSubmitComment">确认</el-button>
          </el-form-item>
        </el-form>

        <comments :Comments='Comments'
                  @notifyFather='notifyFather'
                  v-show="showDetailNews">
        </comments>

      </div>

    </div>
  </div>
</template>


<style scoped>
.news-main {
  background: #ffffff;
  border-radius: 8px;
  min-height: 36px;
  padding: 20px;
  margin-bottom: 16px;
  margin-top: 16px;
}
.user-avatar {
  margin-top: 2vw;
  margin-right: 2vw;
}
.news-content {
  font-size: 18px;
  text-align: left;
  margin-top: 5px;
  margin-bottom: 5px;
  font-weight: bold;
}
.comment-input {
  margin: 0;
  margin-top: 1.5vh;
}

.comment-content {
  text-align: center;
}

.input-btn {
  float: right;
  margin-top: 1.5vh;
}

.refresh-btn {
  width: 60px;
  height: 30px;
  padding: 0 0 0 0;
  margin-top: 1vh;
  margin-bottom: 1vh;
  z-index: 10;
}

.str-btn {
  padding: 0 0 0 0;
  width: 30px;
  height: 30px;
}

.show-detail-btn {
  margin-top: 7px;
  padding: 0;
}

.foot-page {
  display: flex;
  align-items: center;
  text-align: center;
  justify-content: center;
}
</style>

<script>
import Comments from './Comments.vue';
import TopBar from './TopBar.vue';
export default {

  components: { Comments, TopBar },


  mounted () {
    // console.log(this.MyidUser, '初始化的iduser')
    this.getAllNews()

  },
  data () {
    return {
      search: '',
      activeName: 0,
      showAllNews: true,
      showDetailNews: false,
      Comments: [],
      NewsDetail: [],
      commentContent: '',
      isDisable: true,
      commentPlaceHolder: "请输入评论",
      isDeleteBtnShow: true,
      currentIndex: 0,
      currentPage: 1,
      allPages: 1,
      MyidUser: window.sessionStorage.getItem("idUser") == undefined ? 0 : window.sessionStorage.getItem("idUser"),
      newsType: "全部",
      articleData: [{
        title: '第一条资讯',
        address: '新华网',
        comments: '4',
        gaptime: '1'
      }

      ]
    }
  },
  methods: {

    getAllNews () {
      let that = this;
      this.$axios({
        headers: { 'content-Type': 'application/json;charset=utf-8' },
        method: 'get',
        url: "news/all",
        params: {
          page: that.currentPage,
          idUser: that.MyidUser,
          // city: this.d_city
        }
      })
        .then(
          response => {
            // let news = response.data.list
            this.articleData = response.data.list
            this.allPages = response.data.pages
            // console.log('items:::', this.articleData)
          }
        )
        .catch(function (error) {
          // console.log(error);
        });
    },

    Refresh () {
      // 刷新页面，参考链接： https://blog.csdn.net/weixin_43885417/article/details/91310674
      // this.reload();
      this.backToTop()
    },

    // 更新一条资讯，如果对某条资讯收藏了，那么只更新当条资讯就行，没必要全局更新      
    updateSingleNews (idNews, isDetail) {
      let that = this;

      this.$axios({
        headers: { 'content-Type': 'application/json;charset=utf-8' },
        method: 'get',
        url: "news/getbyid",
        params: {
          idNews: idNews,
          idUser: that.MyidUser,
          // city: this.d_city
        }


      })
        .then(
          response => {
            if (isDetail) {
              this.NewsDetail[0] = response.data.list
              // this.NewsDetail[0].newsContent = "ssssssssssssssssssssss"
              // console.log('更新了单条资讯之前', this.NewsDetail)
              let tmp = JSON.parse(JSON.stringify(this.NewsDetail))
              this.NewsDetail = tmp
            } else {

              that.articleData[that.currentIndex] = response.data.list
              let tmp = JSON.parse(JSON.stringify(that.articleData))
              // console.log(that.articleData, "更新前")
              that.articleData = tmp
              // console.log(that.articleData, "更新后")
            }
          }
        )
        .catch(function (error) {
          // console.log(error);
        });

    },

    deleteNewsStar (newsObj, isDetail, currentIdx) {
      // console.log(newsObj, "取消收藏")
      let that = this
      that.currentIndex = currentIdx
      // console.log(that.currentIndex, "更新")
      this.$axios({
        headers: { 'content-Type': 'application/json;charset=utf-8' },
        method: 'delete',
        url: "news/deletenewsstars",
        params: {

          idNews: newsObj.idNews,
          idUser: window.sessionStorage.getItem("idUser"),

        }
      })
        .then(
          response => {

            // console.log('取消收藏成功', response.data)
            // that.commentContent = ''
            this.$notify({
              title: '成功',
              message: response.data.msg,
              type: 'success'
            });
            // commentObj.thumbup = true

            let updatedNews = that.updateSingleNews(newsObj.idNews)
            that.updateSingleNews(newsObj.idNews, isDetail)
            // that.$emit("notifyFather", true)
          }
        )
        .catch(function (error) {
          // console.log(error);
          that.$notify({
            title: '错误',
            message: response.data.msg,
            type: 'error'
          });
        });


    },
    addNewsStar (newsObj, isDetail, currentIdx) {
      let that = this
      // console.log(that.NewsDetail)
      that.currentIndex = currentIdx
      // console.log(that.currentIndex, "更新")
      this.$axios({
        headers: { 'content-Type': 'application/json;charset=utf-8' },
        method: 'post',
        url: "news/addnewsstars",
        params: {
          idNews: newsObj.idNews,
          idUser: window.sessionStorage.getItem("idUser"),
          // city: this.d_city
        }

      })
        .then(
          response => {
            that.updateSingleNews(newsObj.idNews, isDetail)
            this.$notify({
              title: '成功',
              message: response.data.msg,
              type: 'success'
            });
          }
        )
        .catch(function (error) {
          // console.log(error);
          that.$notify({
            title: '错误',
            message: "添加收藏失败，出现错误",
            type: 'error'
          });
        });



    },

    notifyFather (msg) {
      // console.log(msg, "父亲更新了")
      this.showDetail(this.NewsDetail[0])
    },

    getNewsByType (newsType) {
      // console.log(newsType, "父亲更新了type")
      this.newsType = newsType

      let that = this;
      if (that.newsType == "全部") {
        that.getAllNews()
        return;
      }
      this.$axios({
        headers: { 'content-Type': 'application/json;charset=utf-8' },
        method: 'get',
        url: "news/type",
        params: {
          page: that.currentPage,
          idUser: that.MyidUser,
          newsType: that.newsType
          // city: this.d_city
        }
      })
        .then(
          response => {
            // let news = response.data.list
            this.articleData = response.data.list
            this.allPages = response.data.pages
            // console.log('items', this.articleData)
          }
        )
        .catch(function (error) {
          // console.log(error);
        });
    },
    previousPage () {
      let that = this;
      if (this.currentPage > 1) {

        that.currentPage -= 1;
      } else {
        that.currentPage = 1;
        return
      }
      if (that.newsType == "全部") {
        that.getAllNews()
      } else {
        that.getNewsByType(that.newsType)
      }
    },

    nextPage () {
      let that = this;
      if (that.allPages > that.currentPage) {
        that.currentPage += 1;
      }
      else {
        that.currentPage = that.allPages
        return
      }
      if (that.newsType == "全部") {
        that.getAllNews()
      } else {
        that.getNewsByType(that.newsType)
      }
    },

    toLogin () {
      this.$router.push("/Login");
    },
    onSubmitComment () {
      // console.log('submit!');
      let that = this
      // console.log(that.NewsDetail)
      this.$axios({
        headers: { 'content-Type': 'application/json;charset=utf-8' },
        method: 'post',
        url: "news/addcomment",
        params: {
          idNews: that.NewsDetail[0].idNews,
          idUser: window.sessionStorage.getItem("idUser"),
          content: that.commentContent
          // city: this.d_city
        }

      })
        .then(
          response => {
            // let news = response.data.list
            // this.Comments = response.data.listComment
            // console.log('cccccccoooo:::', response.data)
            // this.$router.go(0);
            that.showDetail(that.NewsDetail[0], that.currentIndex);
            that.commentContent = ''
            this.$notify({
              title: '成功',
              message: response.data.msg,
              type: 'success'
            });
          }
        )
        .catch(function (error) {
          // console.log(error);
          that.$notify({
            title: '错误',
            message: response.data.msg,
            type: 'error'
          });
        });

    },

    showDetail: function (e, index) {
      // console.log(e, "看看e", index)
      let that = this
      this.showAllNews = false
      this.showDetailNews = true
      this.currentIndex = index

      // console.log("detail", this.showDetailNews, this.showAllNews)
      let temObj = {}
      temObj["newsContent"] = e.newsContent
      temObj["newsComments"] = e.newsComments
      temObj["newsStars"] = e.newsStars
      temObj["newsUpdatetime"] = e.newsUpdatetime
      temObj["idNews"] = e.idNews
      temObj["stared"] = e.stared
      this.NewsDetail[0] = temObj
      // this.NewsDetail = e.idNews
      this.$axios({
        headers: { 'content-Type': 'application/json;charset=utf-8' },
        method: 'get',
        url: "news/comments",
        params: {
          page: 1,
          idNews: e.idNews,
          idUser: window.sessionStorage.getItem("idUser") == undefined ? 0 : window.sessionStorage.getItem("idUser")
          // city: this.d_city
        }

      })
        .then(
          response => {
            // let news = response.data.list
            this.Comments = response.data.list
            // console.log('cccccccoooo:::', this.Comments)
            for (let i in that.Comments) {
              // console.log(that.Comments[i], "cccccccooooo")
              if (window.sessionStorage.getItem("idUser") == that.Comments[i].user.idUser) {
                that.Comments[i]['isShowDelete'] = true
              } else {
                that.Comments[i]['isShowDelete'] = false

              }
            }

            // console.log('cccccccoooo:::', this.Comments)

          }
        )
        .catch(function (error) {
          // console.log(error);
        });
      // this.$router.go(0);

      // console.log("iduser;;;;;", window.sessionStorage.getItem("idUser"))
      if (window.sessionStorage.getItem("idUser") == null) {
        that.commentPlaceHolder = "您还没有登陆，请登陆再发评论"
      } else {
        that.isDisable = false
      }
    },

    // 返回函数，返回最顶端，其实不需要干啥
    backToTop: function () {
      this.showAllNews = true
      this.showDetailNews = false
    }
  },







}

</script>



 